package com.thb.index.util;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.paoding.analysis.analyzer.PaodingAnalyzer;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.thb.business.model.PostersVO;
import com.thb.logs.utils.LogUtils;
import com.thb.utils.Page;

public class IndexUtil {

	private static final Logger logger = LogUtils.getIndexLog();
	/**
	 * yyyy-MM-dd HH:mm
	 */
	private static final String DATESTRING = "yyyy-MM-dd HH:mm";
	/**
	 * yyyy-MM-dd
	 */
	private static final String DATESTRING_DD = "yyyy-MM-dd";
	/**
	 * yyyy-MM-dd HH:mm:ss
	 */
	private static final String DATESTRING_LONG = "yyyy-MM-dd HH:mm:ss";

	private static String FILE_INDEX = "/home/storm/apilucene/luceneIndex";

	/*
	 * static { String path = System.getenv().get("CATALINA_HOME"); if
	 * (!StringUtils.isBlank(path)) { FILE_INDEX = path + "/webapps/lucene/"; }
	 * logger.info("lucene index dictory is" + FILE_INDEX); }
	 */

	public static void createIndex(List<PostersVO> list) {

		try {
			Long startTime = System.currentTimeMillis();

			File indexDir = new File(FILE_INDEX);
			Analyzer luceneAnalyzer = new PaodingAnalyzer();
			// new
			// StandardAnalyzer(Version.LUCENE_44);

			IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44,
					luceneAnalyzer);
			config.setOpenMode(OpenMode.CREATE);
			Directory directory = FSDirectory.open(indexDir);
//			IndexWriter indexWriter = new IndexWriter(directory, config);
			IndexWriter indexWriter = LucenceUtils.getWriter(directory,config);

			for (PostersVO vo : list) {
				addIndexToDocument(vo,indexWriter); 
			}

			indexWriter.commit();

			Long endTime = System.currentTimeMillis();
			logger.info("花费了" + (endTime - startTime) + "毫秒来创建索引文件");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static void addIndexToDocument(PostersVO vo,IndexWriter indexWriter) throws IOException{
		
//		logger.info(String.format("id:[%s],height [%s]", vo.getPosterId(),vo.getHeigth_weight()));
		// createIndex(post);
		Document doc = new Document();
		doc.add(new StringField("All", "All", Store.YES));
//		doc.add(new StringField("pid", vo.getPosterId(), Store.YES));
		
		doc.add(new StringField("pLiveType", String.valueOf(vo
				.getLiveType()), Store.YES));

		if (vo.getAddress() != null) {
			doc.add(new StringField("paddress", vo.getAddress(),
					Store.YES));
		}
//		if (vo.getPosterImageUrl() != null) {
//			doc.add(new StringField("pimageurl",
//					vo.getPosterImageUrl(), Store.YES));
//		}
//
//		if (vo.getPosterLevel() != null) {
//			doc.add(new StringField("plevel", vo.getPosterLevel(),
//					Store.YES));
//		}

//		if (vo.getPosterTitle() != null) {
//			doc.add(new StringField("ptitle", vo.getPosterTitle(),
//					Store.YES));
//		}
//
//		if (vo.getPosterSummary() != null) {
//			doc.add(new TextField("pcontent", vo.getPosterSummary(),
//					Store.YES));
//		}
//
//		if (vo.getActiveId() != null) {
//			doc.add(new StringField("activeid", vo.getActiveId(),
//					Store.YES));
//		}
//
//		if (vo.getPosterType() != null) {
//			doc.add(new StringField("posttype", String.valueOf(vo
//					.getPosterType()), Store.YES));
//		}

		if (vo.getWeekday() != 0) {
			doc.add(new StringField("weekday", String.valueOf(vo
					.getWeekday()), Store.YES));
		}

		if (vo.getCommunity() != null) {
			doc.add(new StringField("community", String.valueOf(vo
					.getCommunity()), Store.NO));
		}

//		if (vo.getInsquare() != null) {
//			doc.add(new StringField("insquare", String.valueOf(vo
//					.getInsquare()), Store.YES));
//		}

		if (vo.getLabel() != null) {
			doc.add(new StringField("label", String.valueOf(vo
					.getLabel()), Store.YES));
		}

		if (vo.getHeigth_weight() != null) {
			doc.add(new StringField("height_width", String.valueOf(vo
					.getHeigth_weight()), Store.YES));
		}

		if (vo.getStartTime() != null) {
			doc.add(new StringField("starttime", String.valueOf(vo
					.getStartTime()), Store.YES));
		} else {
			doc.add(new StringField("starttime", "", Store.YES));
		}

		if (vo.getEndTime() != null) {
			doc.add(new StringField("endtime", String.valueOf(vo
					.getEndTime()), Store.YES));
		} else {
			doc.add(new StringField("endtime", "", Store.YES));
		}

		if (vo.getStartDate() != null) {
			SimpleDateFormat format = new SimpleDateFormat(
					DATESTRING_LONG);
			Date d;
			try {
				d = format.parse(vo.getStartDate());
				SimpleDateFormat format1 = new SimpleDateFormat(
						DATESTRING);
				String s = format1.format(d);
				doc.add(new StringField("startdate", s, Store.YES));
			} catch (ParseException e) {
				e.printStackTrace();
			}

		}

		if (vo.getEndDate() != null) {
			try {
				SimpleDateFormat format = new SimpleDateFormat(
						DATESTRING_LONG);
				Date d = format.parse(vo.getEndDate());
				SimpleDateFormat format1 = new SimpleDateFormat(
						DATESTRING);
				String s = format1.format(d);
				doc.add(new StringField("enddate", s, Store.YES));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

//		if (vo.getPosterCreateDate() != null) {
//			Date d = new Date(vo.getPosterCreateDate().getTime());
//			SimpleDateFormat format = new SimpleDateFormat(
//					DATESTRING_LONG);
//			String s = format.format(d);
//			doc.add(new StringField("pCreateTime", s, Store.YES));
//		}

		indexWriter.addDocument(doc);
	
	}

	public static void updateIndex(PostersVO vo) {

		try {
			Long startTime = System.currentTimeMillis();
			File indexDir = new File(FILE_INDEX);
			Analyzer luceneAnalyzer = new PaodingAnalyzer();

			IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44,
					luceneAnalyzer);
			config.setOpenMode(OpenMode.APPEND);
			Directory directory = FSDirectory.open(indexDir);
//			IndexWriter indexWriter = new IndexWriter(directory, config);
			
			IndexWriter indexWriter = LucenceUtils.getWriter(directory,config);
			
//			Term term = new Term("pid",vo.getPosterId());
//			indexWriter.deleteDocuments(term);
			
			addIndexToDocument(vo, indexWriter);

			indexWriter.commit();

			Long endTime = System.currentTimeMillis();
			logger.info("花费了" + (endTime - startTime) + "毫秒来创建索引文件");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void deleteIndex(String pid) {

		try {
			Long startTime = System.currentTimeMillis();
			File indexDir = new File(FILE_INDEX);
			Analyzer luceneAnalyzer = new PaodingAnalyzer();

			IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44,
					luceneAnalyzer);
			config.setOpenMode(OpenMode.APPEND);
			Directory directory = FSDirectory.open(indexDir);
//			IndexWriter indexWriter = new IndexWriter(directory, config);
			
			IndexWriter indexWriter = LucenceUtils.getWriter(directory,config);
			
			Term term = new Term("pid",pid);
			indexWriter.deleteDocuments(term);

			indexWriter.commit();

			Long endTime = System.currentTimeMillis();
			logger.info("花费了" + (endTime - startTime) + "毫秒来创建索引文件");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Page<JSONObject> searchPoster(String keyword, int curPage,String posterUri) {
		
		long begin = System.currentTimeMillis();

		List<JSONObject> pList = new ArrayList<JSONObject>();
		try {
			/**
			 * 同时搜索name和descr两个field，并设定它们在搜索结果排序过程中的权重，权重越高，排名越靠前
			 * 为了后面解释score问题的方便，这里设置相同的权重
			 * */
			IndexReader reader = null;
			reader = DirectoryReader.open(FSDirectory
					.open(new File(FILE_INDEX)));
			IndexSearcher searcher = new IndexSearcher(reader);

			BooleanQuery booleanQuery = new BooleanQuery();
			if (keyword == null || "".equals(keyword)) {
				Query query = new TermQuery(new Term("all", "all"));
				booleanQuery.add(query, BooleanClause.Occur.MUST);

			} else {
				Map<String, Float> boosts = new HashMap<String, Float>();
				boosts.put("pcontent", 1.0f);
				boosts.put("ptitle", 2.0f);

				String[] fields = new String[] { "pcontent", "ptitle" };
				Analyzer analyzer = new PaodingAnalyzer();// new
															// StandardAnalyzer(Version.LUCENE_44);

				/**
				 * 用MultiFieldQueryParser类实现对同一关键词的跨域搜索
				 * */
				MultiFieldQueryParser parser = new MultiFieldQueryParser(
						Version.LUCENE_44, fields, analyzer, boosts);
				Query query = parser.parse(keyword);

				booleanQuery.add(query, BooleanClause.Occur.MUST);
			}

			// Query query = MultiFieldQueryParser.parse(Version.LUCENE_44,
			// keyword, fields, flags, analyzer);

			TopDocs results1 = searcher.search(booleanQuery, 10, new Sort(
					new SortField("createtime", SortField.Type.LONG)));

			int total = results1.totalHits;
			int totalPage = total % Page.pageSize == 0 ? total / Page.pageSize
					: total / Page.pageSize + 1;
			int searchTotal = curPage * Page.pageSize;
			total = searchTotal >= total ? total : searchTotal;
			
			int from = (curPage-1)*Page.pageSize;

			if (total == 0) {
				return new Page<JSONObject>(curPage, totalPage, pList);
			}

			TopDocs results2 = searcher.search(booleanQuery, total, new Sort(
					new SortField("createtime", SortField.Type.LONG)));

			ScoreDoc[] hits2 = results2.scoreDocs;
			logger.info("查找[" + keyword + "]有" + hits2.length + "个结果");
			try {
				pList = generateResults(hits2, searcher,from,posterUri);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			long end = System.currentTimeMillis();
			
			logger.info(String.format("this search consume [%s] milliseconds", end-begin));

			return new Page<JSONObject>(curPage, totalPage, pList);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static JSONObject findByPid(String pid) {
		
		logger.info(String.format(" findByPid : pid:%s", pid));

		JSONObject object = new JSONObject();
		try {
			IndexReader reader = null;
			reader = DirectoryReader.open(FSDirectory
					.open(new File(FILE_INDEX)));
			IndexSearcher searcher = new IndexSearcher(reader);

			BooleanQuery booleanQuery = new BooleanQuery();

			if (pid != null) {
				Query typeQuery = new TermQuery(new Term("pid",
						String.valueOf(pid)));
				booleanQuery.add(typeQuery, BooleanClause.Occur.SHOULD);
			}
			
			Map<String, Float> boosts = new HashMap<String, Float>();
			boosts.put("pid", 1.0f);

			String[] fields = new String[] { "pid" };
			Analyzer analyzer = new PaodingAnalyzer();// new
														// StandardAnalyzer(Version.LUCENE_44)

			/**
			 * 用MultiFieldQueryParser类实现对同一关键词的跨域搜索
			 * */
			MultiFieldQueryParser parser = new MultiFieldQueryParser(
					Version.LUCENE_44, fields, analyzer, boosts);
			Query query;
			try {
				query = parser.parse(pid);
				booleanQuery.add(query, BooleanClause.Occur.SHOULD);
			} catch (org.apache.lucene.queryparser.classic.ParseException e) {
				e.printStackTrace();
			}
			
			TopDocs results2 = searcher.search(booleanQuery, 1, new Sort(
					new SortField("createtime", SortField.Type.LONG)));

			ScoreDoc[] hits2 = results2.scoreDocs;
			logger.info("find [" + hits2.length + "] reaults");
			
			Document doc = searcher.doc(hits2[0].doc);

			object.put("content", doc.get("pcontent"));
			return object;

		} catch (IOException e) {
			e.printStackTrace();
		}
		return object;
	}
	
	/**
	 * 在页面日历页面跳转中调用
	 * @param pid
	 * @param posterUri
	 * @return
	 */
	public static JSONObject findAllByPid(String pid,String posterUri) {
		
		logger.info(String.format(" findByPid : pid:%s", pid));

		JSONObject object = new JSONObject();
		try {
			IndexReader reader = null;
			reader = DirectoryReader.open(FSDirectory
					.open(new File(FILE_INDEX)));
			IndexSearcher searcher = new IndexSearcher(reader);

			BooleanQuery booleanQuery = new BooleanQuery();

			if (pid != null) {
				Query typeQuery = new TermQuery(new Term("pid",
						String.valueOf(pid)));
				booleanQuery.add(typeQuery, BooleanClause.Occur.SHOULD);
			}
			
			Map<String, Float> boosts = new HashMap<String, Float>();
			boosts.put("pid", 1.0f);

			String[] fields = new String[] { "pid" };
			Analyzer analyzer = new PaodingAnalyzer();// new
														// StandardAnalyzer(Version.LUCENE_44)

			/**
			 * 用MultiFieldQueryParser类实现对同一关键词的跨域搜索
			 * */
			MultiFieldQueryParser parser = new MultiFieldQueryParser(
					Version.LUCENE_44, fields, analyzer, boosts);
			Query query;
			try {
				query = parser.parse(pid);
				booleanQuery.add(query, BooleanClause.Occur.SHOULD);
			} catch (org.apache.lucene.queryparser.classic.ParseException e) {
				e.printStackTrace();
			}
			
			TopDocs results2 = searcher.search(booleanQuery, 1, new Sort(
					new SortField("createtime", SortField.Type.LONG)));

			ScoreDoc[] hits2 = results2.scoreDocs;
			logger.info("find [" + hits2.length + "] reaults");
			
			Document doc = searcher.doc(hits2[0].doc);

			List<JSONObject> jList = generateResults(hits2, searcher, 0, posterUri);
			JSONObject o = jList.get(0);
			o.put("content", doc.get("pcontent"));
			return o;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}


	public static Page<JSONObject> searchPoster(int type,String key,
			String begin, String end, int curPage, String insquare,
			String communityId,String posterUri,String label,int isRecently) {
		
		long begint = System.currentTimeMillis();
		
		logger.info(String.format("searchPoster :  type:%s,key:%s,begin:%s,end:%s,curPage:%s,insquare:%s,communityId:%s,label:%s,isRecently:%s", type,key,begin,end,curPage,insquare,communityId,label,isRecently));


		try {
			/**
			 * 同时搜索name和descr两个field，并设定它们在搜索结果排序过程中的权重，权重越高，排名越靠前
			 * 为了后面解释score问题的方便，这里设置相同的权重
			 * */

//			IndexReader reader = null;
//			reader = DirectoryReader.open(FSDirectory
//					.open(new File(FILE_INDEX)));
//			IndexSearcher searcher = new IndexSearcher(reader);
			
			IndexSearcher searcher = LucenceUtils.getSearcher(FSDirectory
					.open(new File(FILE_INDEX)));

			BooleanQuery booleanQuery = new BooleanQuery();
			
			boolean isCondition = false;

			if (begin != null && !begin.equals("")) {

				Query start = new TermRangeQuery("startdate", new BytesRef(
						begin), new BytesRef(end), true, true);
				Query ends = new TermRangeQuery("end", new BytesRef(begin),
						new BytesRef(end), true, true);

				booleanQuery.add(start, BooleanClause.Occur.MUST);
				booleanQuery.add(ends, BooleanClause.Occur.SHOULD);
				
				isCondition = true;
			}

			/*if (type != 0) {
				Query typeQuery = new TermQuery(new Term("posttype",
						String.valueOf(type)));
				booleanQuery.add(typeQuery, BooleanClause.Occur.MUST);
				isCondition = true;
			}*/
			
			if (key != null && !"".equals(key)) {
				Map<String, Float> boosts = new HashMap<String, Float>();
				boosts.put("pcontent", 1.0f);
				boosts.put("ptitle", 2.0f);

				String[] fields = new String[] { "pcontent", "ptitle" };
				Analyzer analyzer = new PaodingAnalyzer();// new
															
				/*BooleanClause.Occur[] flags = { BooleanClause.Occur.SHOULD,
						BooleanClause.Occur.MUST };*/

				/**
				 * 用MultiFieldQueryParser类实现对同一关键词的跨域搜索
				 * */
				MultiFieldQueryParser parser = new MultiFieldQueryParser(
						Version.LUCENE_44, fields, analyzer, boosts);
				Query query = parser.parse(key);

				booleanQuery.add(query, BooleanClause.Occur.MUST);
				isCondition = true;
			}
			
			if (label != null && !"".equals(label)) {
//				Map<String, Float> boosts = new HashMap<String, Float>();
//				boosts.put("label", 2.0f);
//
//				String[] fields = new String[] { "label" };
//				Analyzer analyzer = new PaodingAnalyzer();// new
//															
//				MultiFieldQueryParser parser = new MultiFieldQueryParser(
//						Version.LUCENE_44, fields, analyzer, boosts);
//				Query query = parser.parse(label);
				
				Query query = new WildcardQuery(new Term("label", "*"+ label +"*"));

				booleanQuery.add(query, BooleanClause.Occur.MUST);
				isCondition = true;
			}

			if (insquare.equals("1")) {
				Query typeQuery = new TermQuery(new Term("insquare",
						String.valueOf(insquare)));
				booleanQuery.add(typeQuery, BooleanClause.Occur.MUST);
				isCondition = true;
			}

			if (communityId != null && !"".equals(communityId)) {
				Query typeQuery = new TermQuery(new Term("community",
						String.valueOf(communityId)));
				booleanQuery.add(typeQuery, BooleanClause.Occur.MUST);
				isCondition = true;
			}
			/*
			if(isRecently == 1){
				Date now = new Date();
				SimpleDateFormat df = new SimpleDateFormat(DATESTRING_LONG);
				String nowString = df.format(now);
				Calendar cal = Calendar.getInstance();
				cal.setTime(now);
				cal.add(Calendar.DAY_OF_MONTH, -1);
				Date yestoday = cal.getTime();
				String yestodayString = df.format(yestoday);
				Query start = new TermRangeQuery("pCreateTime", new BytesRef(
						yestodayString), new BytesRef(nowString), true, true);

				booleanQuery.add(start, BooleanClause.Occur.MUST);
				isCondition = true;
			}*/

			// 没有查询条件就是查询所有
			if (!isCondition) {
				Query query = new TermQuery(new Term("All", "All"));
				booleanQuery.add(query, BooleanClause.Occur.MUST);
			}

			TopDocs results2 = searcher.search(booleanQuery, 250, new Sort(
					new SortField("pCreateTime", SortField.Type.STRING,true)));

			// TopDocs results1 = searcher.search(booleanQuery,total,new
			// Sort(new SortField("createtime", SortField.Type.LONG)));

			int total = results2.totalHits;
			logger.info("find [" + total + "] reaults all");
			int totalPage = total % Page.pageSize == 0 ? (total / Page.pageSize)
					: (total / Page.pageSize + 1);
			int searchTotal = curPage * Page.pageSize;
			total = searchTotal >= total ? total : searchTotal;
			
			int from = (curPage -1)*Page.pageSize;

			List<JSONObject> pList = new ArrayList<JSONObject>();

			if (total == 0) {
				return new Page<JSONObject>(curPage, totalPage, pList);
			}

			TopDocs hits = searcher.search(booleanQuery, total, new Sort(
					new SortField("pCreateTime", SortField.Type.STRING,true)));

			ScoreDoc[] hits2 = hits.scoreDocs;
			logger.info("find [" + hits2.length + "] reaults");

			try {
				pList = generateResults(hits2, searcher,from,posterUri);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			long endt = System.currentTimeMillis();
			
			logger.info(String.format("this search consume [%s] milliseconds", endt-begint));

			return new Page<JSONObject>(curPage, totalPage, pList);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Page<JSONObject>(0, 0, null);
	}

	private static List<JSONObject> generateResults(ScoreDoc[] docs,
			IndexSearcher searcher,int from,String psterUri) throws IOException, ParseException {

		List<JSONObject> pList = new ArrayList<JSONObject>();

		for (int i = from; i < docs.length; i++) {

			Document doc = searcher.doc(docs[i].doc);
			JSONObject object = new JSONObject();
			object.put("postercode", doc.get("pid"));
			object.put("posterurl", psterUri+doc.get("pimageurl"));
			object.put("activitytheme", doc.get("ptitle"));
			object.put("address", doc.get("paddress"));
			object.put("livetype", doc.get("pLiveType"));
			object.put("activeid", doc.get("activeid"));
			object.put("label", doc.get("label"));
			object.put("startDate", doc.get("startdate"));
			object.put("height_width", doc.get("height_width"));

			if (doc.get("pLiveType") == null || "".equals(doc.get("pLiveType"))) {
				object.put("activitydate", doc.get("pCreateTime"));
			} else if (doc.get("pLiveType").equals("1")) {
				String date = doc.get("startdate");
				SimpleDateFormat f = new SimpleDateFormat(DATESTRING);
				SimpleDateFormat fd = new SimpleDateFormat(DATESTRING_DD);
				Date start = f.parse(date);
				String s = fd.format(start);
				object.put(
						"activitydate",
						String.format("%s %s-%s", s, doc.get("starttime"),
								doc.get("endtime")));
			} else if (doc.get("pLiveType").equals("3")) {
				String datestart = doc.get("startdate");
				String dateend = doc.get("enddate");
				SimpleDateFormat f = new SimpleDateFormat(DATESTRING);
				SimpleDateFormat fd = new SimpleDateFormat(DATESTRING_DD);
				Date start = f.parse(datestart);
				String sstart = fd.format(start);

				Date sdateend = f.parse(dateend);
				String send = fd.format(sdateend);

				Integer week = Integer.valueOf(doc.get("weekday"));
				String binary = Integer.toBinaryString(week);
				binary = String.format("%07d", Integer.valueOf(binary));
				StringBuilder weeks = new StringBuilder("每");
				List<String> sList = new ArrayList<String>();
				if (binary.substring(1, 2).equals("1")) {
					sList.add("周一");
				}
				if (binary.substring(2, 3).equals("1")) {
					sList.add("周二");
				}
				if (binary.substring(3, 4).equals("1")) {
					sList.add("周三");
				}
				if (binary.substring(4, 5).equals("1")) {
					sList.add("周四");
				}
				if (binary.substring(5, 6).equals("1")) {
					sList.add("周五");
				}
				if (binary.substring(6, 7).equals("1")) {
					sList.add("周六");
				}
				if (binary.substring(7).equals("1")) {
					sList.add("周日");
				}

				for (String s : sList) {
					weeks.append(s).append(",");
				}

				String str = weeks.toString();

				str = str.substring(0, str.length() - 1);

				object.put(
						"activitydate",
						String.format("%s至%s %s %s-%s", sstart, send, str,
								doc.get("starttime"), doc.get("endtime")));
			} else if (doc.get("pLiveType").equals("2")) {
				String date = doc.get("startdate");
				String enddate = doc.get("enddate");
				SimpleDateFormat f = new SimpleDateFormat(DATESTRING);
				SimpleDateFormat fd = new SimpleDateFormat(DATESTRING_DD);
				Date start = f.parse(date);
				String s = fd.format(start);

				Date estart = f.parse(enddate);
				String es = fd.format(estart);
				object.put(
						"activitydate",
						String.format("%s至%s %s-%s", s, es,
								doc.get("starttime"), doc.get("endtime")));
			}

			pList.add(object);

		}

		return pList;
	}

	/**
	 * check Index is Existed
	 * 
	 * @return true or false
	 */

	public boolean isIndexExisted() {
		try {
			File dir = new File(FILE_INDEX);
			if (dir.listFiles().length > 0)
				return true;
			else
				return false;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/*
	 * Document doc = searcher.doc(hits2[i].doc);
	 * 
	 * JSONObject object = new JSONObject(); object.put("postercode",
	 * doc.get("pid")); object.put("posterurl", doc.get("pimageurl"));
	 * object.put("activitytheme", doc.get("ptitle")); //
	 * object.put("activitydate", doc.get("startdate")); object.put("address",
	 * doc.get("padress")); object.put("livetype", doc.get("pLiveType"));
	 * object.put("activeid", doc.get("activeid")); object.put("content",
	 * doc.get("pcontent")); object.put("address", doc.get("padress"));
	 * object.put("label", doc.get("label")); object.put("noteTime", ""); if
	 * (doc.get("pLiveType") == null || "".equals(doc.get("pLiveType"))) {
	 * object.put("activitydate", doc.get("pCreateTime")); } else if
	 * (doc.get("pLiveType").equals("1")) { String date = doc.get("startdate");
	 * SimpleDateFormat f = new SimpleDateFormat(DATESTRING); SimpleDateFormat
	 * fd = new SimpleDateFormat(DATESTRING_DD); Date start = f.parse(date);
	 * String s = fd.format(start); object.put("activitydate",
	 * String.format("%s %s-%s", s, doc.get("starttime"), doc.get("endtime")));
	 * } else if (doc.get("pLiveType").equals("3")) { String datestart =
	 * doc.get("startdate"); String dateend = doc.get("enddate");
	 * SimpleDateFormat f = new SimpleDateFormat(DATESTRING); SimpleDateFormat
	 * fd = new SimpleDateFormat(DATESTRING_DD); Date start =
	 * f.parse(datestart); String sstart = fd.format(start);
	 * 
	 * Date sdateend = f.parse(dateend); String send = fd.format(sdateend);
	 * 
	 * Integer week = Integer.valueOf(doc.get("weekday")); String binary =
	 * Integer.toBinaryString(week); binary = String.format("%07d",
	 * Integer.valueOf(binary)); StringBuilder weeks = new StringBuilder("每");
	 * List<String> sList = new ArrayList<String>(); if (binary.substring(1,
	 * 2).equals("1")) { sList.add("周一"); } if (binary.substring(2,
	 * 3).equals("1")) { sList.add("周二"); } if (binary.substring(3,
	 * 4).equals("1")) { sList.add("周三"); } if (binary.substring(4,
	 * 5).equals("1")) { sList.add("周四"); } if (binary.substring(5,
	 * 6).equals("1")) { sList.add("周五"); } if (binary.substring(6,
	 * 7).equals("1")) { sList.add("周六"); } if (binary.substring(7).equals("1"))
	 * { sList.add("周日"); }
	 * 
	 * for (String s : sList) { weeks.append(s).append(","); }
	 * 
	 * String str = weeks.toString();
	 * 
	 * str = str.substring(0, str.length() - 1);
	 * 
	 * object.put("activitydate", String.format("%s至%s %s %s-%s", sstart, send,
	 * str, doc.get("starttime"), doc.get("endtime"))); } else if
	 * (doc.get("pLiveType").equals("1")) { String date = doc.get("startdate");
	 * String enddate = doc.get("enddate"); SimpleDateFormat f = new
	 * SimpleDateFormat(DATESTRING); SimpleDateFormat fd = new
	 * SimpleDateFormat(DATESTRING_DD); Date start = f.parse(date); String s =
	 * fd.format(start);
	 * 
	 * Date estart = f.parse(enddate); String es = fd.format(estart);
	 * object.put( "activitydate", String.format("%s-%s %s-%s", s, es,
	 * doc.get("starttime"), doc.get("endtime"))); }
	 * 
	 * pList.add(object);
	 */

}
